﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CMSMVC4.Filters;

namespace CMSMVC4.Areas.Admin.Controllers
{
    [Authorize(Roles = "Admin,Slideshow")]
    public class SlideshowController : Controller
    {
        //
        // GET: /Admin/Slideshow/
        readonly CMSMVC4Entities _db = new CMSMVC4Entities();
        public ActionResult Index()
        {
            ViewBag.M = new CommandSql().GetParrentByMenu("/Admin/SlideShow").Rows[0]["Id"];
            var data = _db.Slides.ToList();
            return View(data);
        }

        [HttpPost]
        public ActionResult Index(List<Slide> model)
        {
            foreach (var slide in model)
            {
                var row = _db.Slides.FirstOrDefault(x => x.Id == slide.Id);
                if (row == null) continue;
                row.Image = slide.Image;
                row.Url = slide.Url;
                _db.SaveChanges();
            }
            ModelState.AddModelError("", "Saved");
            return RedirectToAction("Index");
        }

        public ActionResult Add()
        {
            ViewBag.M = new CommandSql().GetParrentByMenu("/Admin/SlideShow").Rows[0]["Id"];
            return View();
        }

        [HttpPost]
        public ActionResult Add(Slide model)
        {
            if (ModelState.IsValid)
            {
                var sl = new Slide {Image = model.Image, Url = model.Url};
                _db.Slides.AddObject(sl);
                _db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(model);
        }


        //
        // GET: /Admin/SlideShow/Delete
        [HttpGet]
        public ActionResult Xoa(int id)
        {
            return PartialView();
        }

        [HttpPost]
        public ActionResult Xoa(string[] id)
        {
            if (id != null)
            {
                foreach (var i in id)
                {
                    int idcomment;
                    int.TryParse(i, out idcomment);
                    var row = _db.Slides.FirstOrDefault(x => x.Id == idcomment);
                    _db.Slides.DeleteObject(row);
                    _db.SaveChanges();
                }
            }
            return Json(string.Empty, JsonRequestBehavior.AllowGet);
        }

    }
}
